"""
示例用法脚本
演示如何使用示例项目
"""

import os
import json
import random
from datetime import datetime, timedelta
from typing import List, Dict, Any

# 导入示例项目
from sample_project import Application, CONFIG

# 生成模拟数据
def generate_mock_data(count: int = 100) -> List[Dict[str, Any]]:
    """
    生成模拟数据
    
    Args:
        count: 数据项数量
        
    Returns:
        模拟数据列表
    """
    data = []
    types = ["type_a", "type_b", "type_c", "type_d"]
    categories = ["cat_1", "cat_2", "cat_3"]
    
    now = datetime.now()
    
    for i in range(count):
        # 随机生成一个过去30天内的时间戳
        days_ago = random.randint(0, 30)
        timestamp = (now - timedelta(days=days_ago)).timestamp()
        
        item = {
            "id": f"item_{i}",
            "type": random.choice(types),
            "category": random.choice(categories),
            "value": random.uniform(10, 1000),
            "is_active": random.choice([True, False]),
            "created_at": timestamp,
            "tags": random.sample(["tag1", "tag2", "tag3", "tag4", "tag5"], random.randint(1, 3)),
            "metadata": {
                "source": f"source_{random.randint(1, 5)}",
                "priority": random.randint(1, 5)
            }
        }
        
        # 有些项目有额外的值列表
        if random.random() > 0.7:
            item["values"] = [random.uniform(1, 100) for _ in range(random.randint(3, 10))]
        
        data.append(item)
    
    return data

# 模拟API响应
class MockApiResponse:
    """模拟API响应类"""
    
    def __init__(self, data: List[Dict[str, Any]]):
        """
        初始化模拟API响应
        
        Args:
            data: 模拟数据
        """
        self.data = data
    
    def get_response(self, endpoint: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
        """
        获取模拟API响应
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            模拟API响应
        """
        # 模拟分页
        page = int(params.get("page", 1)) if params else 1
        per_page = int(params.get("per_page", 20)) if params else 20
        
        start_idx = (page - 1) * per_page
        end_idx = start_idx + per_page
        
        # 模拟过滤
        filtered_data = self.data
        if params and "type" in params:
            filtered_data = [item for item in filtered_data if item["type"] == params["type"]]
        
        # 分页数据
        paged_data = filtered_data[start_idx:end_idx]
        
        return {
            "items": paged_data,
            "meta": {
                "total": len(filtered_data),
                "page": page,
                "per_page": per_page,
                "pages": (len(filtered_data) + per_page - 1) // per_page
            }
        }

# 模拟API客户端
def mock_api_client(app: Application, mock_data: List[Dict[str, Any]]) -> None:
    """
    替换应用中的API客户端为模拟版本
    
    Args:
        app: 应用实例
        mock_data: 模拟数据
    """
    mock_api = MockApiResponse(mock_data)
    
    # 替换API客户端的fetch_data方法
    original_fetch_data = app.data_processor.fetch_data
    
    def mock_fetch_data(endpoint: str, params: Dict[str, Any] = None, use_cache: bool = True) -> Dict[str, Any]:
        # 如果使用缓存且缓存存在，则使用缓存
        if use_cache:
            cache_key = f"{endpoint}:{json.dumps(params or {})}"
            cached_data = app.data_processor.cache.get(cache_key)
            if cached_data is not None:
                return cached_data
        
        # 否则使用模拟API
        response = mock_api.get_response(endpoint, params)
        
        # 如果需要缓存，则缓存结果
        if use_cache:
            cache_key = f"{endpoint}:{json.dumps(params or {})}"
            app.data_processor.cache.set(cache_key, response)
        
        return response
    
    # 替换方法
    app.data_processor.fetch_data = mock_fetch_data

def main():
    """主函数"""
    # 创建输出目录
    output_dir = "output"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 生成模拟数据
    mock_data = generate_mock_data(200)
    
    # 创建应用实例
    app = Application()
    
    # 使用模拟API客户端
    mock_api_client(app, mock_data)
    
    # 运行应用 - 获取所有数据
    print("获取所有数据...")
    results = app.run("items", {"page": 1, "per_page": 50})
    
    # 导出结果
    print("导出结果...")
    exported_files = app.export_results(results, output_dir)
    
    # 打印导出的文件路径
    print("\n导出的文件:")
    for key, path in exported_files.items():
        print(f"{key}: {path}")
    
    # 按类型分组运行
    print("\n按类型分组...")
    grouped_results = app.run("items", {"group_by": "type"})
    
    # 导出分组结果
    grouped_files = app.export_results(grouped_results, output_dir)
    
    # 打印导出的文件路径
    print("\n导出的分组文件:")
    for key, path in grouped_files.items():
        print(f"{key}: {path}")
    
    # 生成趋势报告
    print("\n生成趋势报告...")
    from sample_project.report_generator import ReportGenerator
    trend_report = app.report_generator.generate_trend_report(
        mock_data, "created_at", interval="day"
    )
    
    # 导出趋势报告
    trend_path = os.path.join(output_dir, f"trend_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json")
    app.data_processor.export_to_json(trend_report, trend_path)
    print(f"趋势报告: {trend_path}")
    
    # 清理资源
    print("\n清理资源...")
    app.cleanup()
    print("完成!")

if __name__ == "__main__":
    main()